package insight.web.delegates;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

public class ReflectionDelegate {

	public static <T extends Annotation> Field[] getAnnotatedFields(
			Class<?> clazz, Class<T> annotClass) {
		ArrayList<Field> fields = new ArrayList<Field>();
		for (Field field : clazz.getDeclaredFields()) {
			if (field.getAnnotation(annotClass) != null) {
				fields.add(field);
			}
		}
		
		return fields.toArray(new Field[fields.size()]);
	}

	public static Method getSetterMethod(Field field) {
		Method[] methods = field.getDeclaringClass().getMethods();
		System.out.println("Found " + methods.length + " method(s).");
		for (Method method : methods) {
			System.out.println("Checking method " + method.getName());
			if (Modifier.isPublic(method.getModifiers())
					&& method.getReturnType().equals(void.class)
					&& method.getParameterTypes().length == 1
					&& method.getParameterTypes()[0].equals(field.getType())
					&& method.getName().equalsIgnoreCase("set" + field.getName())) {
				return method;
			}
		}
		return null;
	}
}
